﻿using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using SupplierCustomerManagement.Domain.ReportForms;

namespace SupplierCustomerManagement.Infrastructure
{
    public class SupplierDbContext : DbContext
    {
        public SupplierDbContext(DbContextOptions options) : base(options)
        {
        }

        // 客户相关实体
        public DbSet<Customer> Customers { get; set; }
        public DbSet<CustomerContact> CustomerContacts { get; set; }

        // 供应商相关实体
        public DbSet<Supplier> Suppliers { get; set; }
        public DbSet<SupplierContact> SupplierContacts { get; set; }

        // 共享实体
        public DbSet<ServicePersonnel> ServicePersonnels { get; set; }
        public DbSet<BankAccount> BankAccounts { get; set; }
        public DbSet<DiscountScheme> DiscountSchemes { get; set; }
        public DbSet<DiscountScheme.DiscountSchemeItem> DiscountSchemeItems { get; set; }
        public DbSet<ProductPurchasePrice> ProductPurchasePrices { get; set; }
        public DbSet<Attachment> Attachments { get; set; }
        public DbSet<Sheep> Sheeps { get; set; }
        public DbSet<SheepInventorySummary> SheepInventorySummaries { get; set; }
        public DbSet<SheepInventoryHistory> SheepInventoryHistories { get; set; }
        public DbSet<LambingRecord> LambingRecords { get; set; }
        public DbSet<LambDetail> LambDetails { get; set; }
        public DbSet<BreedingRecord> BreedingRecords { get; set; }
        public DbSet<PregnancyCheck> PregnancyChecks { get; set; }
        public DbSet<EweReproductiveStatus> EweReproductiveStatuses { get; set; }
        public DbSet<ProductionRecord> ProductionRecords { get; set; }
        public DbSet<ProductionSummary> ProductionSummaries { get; set; }
        public DbSet<Farm> Farms { get; set; }
        public DbSet<SystemUser> SystemUsers { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 配置实体关系和约束
            ConfigureCustomerEntities(modelBuilder);
            ConfigureSupplierEntities(modelBuilder);
            ConfigureSharedEntities(modelBuilder);
            ConfigureReportFormsEntities(modelBuilder);
        }

        /// <summary>
        /// 配置客户相关实体
        /// </summary>
        private void ConfigureCustomerEntities(ModelBuilder modelBuilder)
        {
            // Customer配置
            modelBuilder.Entity<Customer>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.CustomerCode).IsRequired().HasMaxLength(50);
                entity.Property(e => e.Name).IsRequired().HasMaxLength(200);
                entity.Property(e => e.Type).IsRequired().HasMaxLength(20);
                entity.Property(e => e.Status).IsRequired().HasMaxLength(20);
                entity.Property(e => e.EntryUnit).IsRequired().HasMaxLength(100);
                entity.Property(e => e.UsageUnit).IsRequired().HasMaxLength(100);

                // 自引用关系
                entity.HasOne<Customer>()
                      .WithMany()
                      .HasForeignKey(e => e.SuperiorCustomerId)
                      .OnDelete(DeleteBehavior.Restrict);

                // 索引
                entity.HasIndex(e => e.CustomerCode).IsUnique();
                entity.HasIndex(e => e.Name);
                entity.HasIndex(e => e.Status);
                entity.HasIndex(e => e.Type);
            });

            // CustomerContact配置
            modelBuilder.Entity<CustomerContact>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.ContactPerson).IsRequired().HasMaxLength(100);

                // 与Customer的关系
                entity.HasOne<Customer>()
                      .WithMany()
                      .HasForeignKey(e => e.CustomerId)
                      .OnDelete(DeleteBehavior.Cascade);
            });
        }

        /// <summary>
        /// 配置供应商相关实体
        /// </summary>
        private void ConfigureSupplierEntities(ModelBuilder modelBuilder)
        {
            // Supplier配置
            modelBuilder.Entity<Supplier>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.SupplierCode).IsRequired().HasMaxLength(50);
                entity.Property(e => e.SupplierName).IsRequired().HasMaxLength(200);
                entity.Property(e => e.SupplierType).IsRequired().HasMaxLength(20);
                entity.Property(e => e.Status).IsRequired().HasMaxLength(20);
                entity.Property(e => e.EntryUnit).IsRequired().HasMaxLength(100);
                entity.Property(e => e.UsageUnit).IsRequired().HasMaxLength(100);

                // 索引
                entity.HasIndex(e => e.SupplierCode).IsUnique();
                entity.HasIndex(e => e.SupplierName);
                entity.HasIndex(e => e.Status);
            });

            // SupplierContact配置
            modelBuilder.Entity<SupplierContact>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.ContactPerson).IsRequired().HasMaxLength(100);

                // 与Supplier的关系
                entity.HasOne<Supplier>()
                      .WithMany()
                      .HasForeignKey(e => e.SupplierId)
                      .OnDelete(DeleteBehavior.Cascade);

                // 索引
                entity.HasIndex(e => e.SupplierId);
                entity.HasIndex(e => e.IsDefault);
            });
        }

        /// <summary>
        /// 配置共享实体
        /// </summary>
        private void ConfigureSharedEntities(ModelBuilder modelBuilder)
        {
            // ServicePersonnel配置
            modelBuilder.Entity<ServicePersonnel>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.RelatedEntityType).IsRequired().HasMaxLength(50);
                entity.Property(e => e.ServiceType).IsRequired().HasMaxLength(50);
                entity.Property(e => e.Name).IsRequired().HasMaxLength(100);
            });

            // BankAccount配置
            modelBuilder.Entity<BankAccount>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.RelatedEntityType).IsRequired().HasMaxLength(50);
                entity.Property(e => e.BankName).IsRequired().HasMaxLength(100);
                entity.Property(e => e.AccountName).IsRequired().HasMaxLength(100);
                entity.Property(e => e.OpeningBank).IsRequired().HasMaxLength(200);
                entity.Property(e => e.AccountNumber).IsRequired().HasMaxLength(50);
                entity.Property(e => e.AccountType).IsRequired().HasMaxLength(20);
                entity.Property(e => e.AccountProperty).IsRequired().HasMaxLength(20);
            });

            // DiscountScheme配置
            modelBuilder.Entity<DiscountScheme>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.RelatedEntityType).IsRequired().HasMaxLength(50);
                entity.Property(e => e.SchemeName).IsRequired().HasMaxLength(200);
                entity.Property(e => e.SchemeDescription).IsRequired().HasMaxLength(1000);
                entity.Property(e => e.DiscountType).HasMaxLength(50);
                entity.Property(e => e.DiscountTarget).HasMaxLength(100);
                entity.Property(e => e.SchemeType).HasMaxLength(50);
                entity.Property(e => e.Remarks).HasMaxLength(500);
                entity.Property(e => e.ApprovedBy).HasMaxLength(100);
                entity.Property(e => e.FinancedBy).HasMaxLength(100);
                entity.Property(e => e.PreparedBy).HasMaxLength(100);

                // 与DiscountSchemeItem的关系
                entity.HasMany(e => e.DiscountSchemeItems)
                      .WithOne()
                      .HasForeignKey(e => e.DiscountSchemeId)
                      .OnDelete(DeleteBehavior.Cascade);

                // 索引
                entity.HasIndex(e => e.RelatedEntityId);
                entity.HasIndex(e => e.RelatedEntityType);
                entity.HasIndex(e => e.SchemeName);
            });

            // DiscountSchemeItem配置
            modelBuilder.Entity<DiscountScheme.DiscountSchemeItem>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.DiscountType).IsRequired().HasMaxLength(50);
                entity.Property(e => e.DiscountTarget).IsRequired().HasMaxLength(100);
                entity.Property(e => e.DiscountItem).IsRequired().HasMaxLength(200);
                entity.Property(e => e.DiscountMethod).IsRequired().HasMaxLength(50);
                entity.Property(e => e.SuperiorCustomer).HasMaxLength(200);
                entity.Property(e => e.Deduction).HasPrecision(18, 2);
                entity.Property(e => e.AccrualRate).HasPrecision(5, 4);

                // 索引
                entity.HasIndex(e => e.DiscountSchemeId);
                entity.HasIndex(e => e.DiscountType);
            });

            // ProductPurchasePrice配置
            modelBuilder.Entity<ProductPurchasePrice>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.ProductName).IsRequired().HasMaxLength(200);
                entity.Property(e => e.Specification).IsRequired().HasMaxLength(200);
                entity.Property(e => e.MeasurementUnit).IsRequired().HasMaxLength(50);
                entity.Property(e => e.SchemeName).IsRequired().HasMaxLength(200);

                // 与Supplier的关系
                entity.HasOne<Supplier>()
                      .WithMany()
                      .HasForeignKey(e => e.SupplierId)
                      .OnDelete(DeleteBehavior.Restrict);
            });

            // Attachment配置
            modelBuilder.Entity<Attachment>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.RelatedEntityType).IsRequired().HasMaxLength(50);
                entity.Property(e => e.FileName).IsRequired().HasMaxLength(255);
                entity.Property(e => e.OriginalFileName).IsRequired().HasMaxLength(255);
                entity.Property(e => e.FilePath).IsRequired().HasMaxLength(500);
                entity.Property(e => e.FileType).IsRequired().HasMaxLength(100);
                entity.Property(e => e.FileExtension).IsRequired().HasMaxLength(20);
            });
        }

        private void ConfigureReportFormsEntities(ModelBuilder modelBuilder)
        {
            // 可在此处为报表相关实体做进一步配置
        }
    }
}
